/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.c1202m.connection;

import com.c1202m.hibernate.entities.Server;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.swing.JOptionPane;

/**
 *
 * @author CodeBlue
 */
public class MyConnection {
    
    public static Server server = null;

    /**
     * Method is used to return one connection if connecting successfully.
     * 
     * @return returns one connection.
     * 
     * @exception SQLException is made when there is one error when connecting to database.
     * @exception ClassNotFoundException 
     */
    public static Connection getConnection(Server server) {

        String url = "jdbc:sqlserver://" + server.getServerName() + ":" + server.getPort()
                + ";DatabaseName=" + server.getDatabaseName();
        try {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            Connection cn = DriverManager.getConnection(url, server.getUserName(), server.getPassword());
            return cn;
        } catch (ClassNotFoundException cnfe) {
            JOptionPane.showMessageDialog(null, "Did you forget to import the jdbc library?");
        } catch (SQLException se) {
            System.out.println("Connection failed!");
        }
        return null;
    }
    // check connection to server

    public static boolean checkConnection() {
        Connection cn = null;
        try {
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream(Server.configFile));
            server = (Server) ois.readObject();
            cn = getConnection(server);
            cn.close();
            ois.close();
        } catch (Exception e) {
            return false;
        }
        return cn != null;
    }
}
